// 单链表栈

class Node {
    constructor(data) {
        this.data = data
        this.next = null
    }
}


// 可以自己规定是头结点作为栈顶还是尾结点作为栈顶，这里使用尾结点作为栈顶，头结点作为栈底
class StackLink {
    size = 0
    head = null // 这里代表栈底
    tail = null // 这里代表栈顶

    push(item) {
        const node = new Node(item)
        if (!item) {
            return 
        }
        if (this.size === 0) { // 栈中数据为空
            this.head = node
            this.tail = node 
        } else {
            // 都在尾部插入
            this.tail.next = node
            this.tail = node
        }

        this.size++
        return this.size
    }

    pop() {
        if (this.size === 0) {
            return 
        }
        // 需要找到栈底元素的上一个元素， 让栈顶执向他， 由于不是双向所以只有从栈底开始找
        let current = this.head
        let previous = null
        for (let i = 1; i < this.size; i ++) {
            previous = current
            current = current.next
        }
        const res = current.data
        previous.next = null
        this.tail = previous
        
        this.size --
        return res
    }

    getSize() {
        return this.size
    }

    // 遍历
    print() {
        if (this.size ===0) {
            console.log("空栈")
            return
        }
        let node = this.head
        while (node) {
            console.log(node.data)
            node = node.next
        }
    }
}


const stackLink = new StackLink()

stackLink.push(1)
stackLink.push(2)
stackLink.push(3)
stackLink.print()
console.log("当前栈的长度为:", stackLink.getSize());

console.log("弹出栈的数是:", stackLink.pop());

stackLink.print()

console.log("弹出栈的数是:", stackLink.pop());
stackLink.print()
